package com.map.controller.admin;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.map.dto.TuCengDto;
import com.map.entity.MapTucengDetails;
import com.map.entity.MapTucengPage;
import com.map.entity.Maptuceng;
import com.map.entity.MaptucengStyle;
import com.map.service.TucengService;
import com.map.util.MessageUtil;
import com.map.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/tuceng")
public class TucengController {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private TucengService tucengService;

    @RequestMapping("queryMaptuceng.action")
    public Map<String, Object> queryMaptuceng(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String linecolor,
            @RequestParam(required = false) String fillcolor,
            @RequestParam(required = false) String id,
            @RequestParam(required = false) String sql,
            @RequestParam(required = false) String pageId,
            @RequestParam(defaultValue = "0", required = false) Integer pageIndex,
            @RequestParam(defaultValue = "100", required = false) Integer pageSize
    ) {
        TuCengDto tuCengDto = new TuCengDto()
                .setCode(code)
                .setFillcolor(fillcolor)
                .setFillcolor(linecolor)
                .setId(id)
                .setName(name)
                .setSql(sql)
                .setPageId(pageId);

        Map<String, Object> resultMap = new HashMap<>();
        Page<Maptuceng> maptucengs = tucengService.queryMaptuceng(tuCengDto, pageIndex, pageSize, Sort.Direction.DESC, "id");

        resultMap.clear();
        resultMap.put("data", maptucengs.getContent());
        resultMap.put("total", maptucengs.getTotalPages());

        if (!StringUtil.isEmpty(id) && maptucengs.getContent().size() > 0) {
            Maptuceng mt = maptucengs.getContent().get(0);
            Maptuceng mt1 = null;
            if (StringUtil.isNotEmpty(mt.getLinkId())) {
                tuCengDto = new TuCengDto().setId(mt.getLinkId());
                maptucengs = tucengService.queryMaptuceng(tuCengDto, pageIndex, pageSize, Sort.Direction.DESC, "id");
                mt1 = maptucengs.getContent().get(0);
            }
            Map<String, List> result = new HashMap<String, List>() {{
                put("details", new ArrayList<>());
                put("style", new ArrayList<>());
            }};

            result = getStyle(mt, result);
            result = getStyle(mt1, result);

            resultMap.put("details", result.get("details"));
            resultMap.put("style", result.get("style"));
        }
        resultMap.put("success", true);
        return resultMap;
    }

    private Map<String, List> getStyle(Maptuceng mt, Map<String, List> result) {
        if (StringUtils.isEmpty(mt)) return result;
        if (result.get("style").size() == 0) {
//            List style = jdbcTemplate.queryForList("select  top 1 * from jiyue_map_tucengstyle where layername='" + mt.getLayername() + "' order by updatetime desc");
            Page<MaptucengStyle> style = tucengService.queryMapTuCengStyleRepository(mt.getLayername(), 0, 1, Sort.Direction.DESC, "updatetime");
            result.put("style", style.getContent());
        }
        if (result.get("details").size() == 0) {
            List details;
            if (!StringUtil.isEmpty(mt.getSql())) {
                details = jdbcTemplate.queryForList(mt.getSql());
            } else {
                details = jdbcTemplate.queryForList("select id,name,type,lnglats  from jiyue_map_tucengdetails where layername='" + mt.getLayername() + "' ");
            }
            result.put("details", details);
        }

        return result;
    }


    //模糊查询，id查询，空间查询都
    @RequestMapping("queryMapTucengDetailsByIds.action")
    public Map<String, Object> queryMapTucengDetailsByIds(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            // 关键字取得
            String layers = request.getParameter("layers");

            if (StringUtil.isEmpty(layers)) {
                model.clear();
                model.put("data", "");
                return model;
            }
            JSONArray objects = JSONUtil.parseArray(layers);

            //条件
            Map<String, Object> layerMap = null;
            String ids = "";
            for (Object object : objects) {
                layerMap = (Map<String, Object>) object;
                if (layerMap.containsKey("layer") && StringUtil.isNotEmpty(layerMap.get("layer") + "")) {
                    ids += "," + layerMap.get("layer");
                }

            }
            TuCengDto tuCengDto = new TuCengDto().setIds(ids.replaceFirst(",", ""));
//            List<Map<String, Object>> list = jdbcTemplate.queryForList("select   * from jiyue_map_tuceng" +
//                    " where 1=1 and id in  ('" + ids.replaceFirst(",", "").replaceAll(",", "','") + "') order by id desc ");
            Page<Maptuceng> maptucengs = tucengService.queryMaptuceng(tuCengDto, 0, 999, Sort.Direction.DESC, "id");

//            Maptuceng mt = null;
            Map<String, Object> map = null;
            List details = null;
            List<Map<String, Object>> result = new ArrayList<>();
            if (maptucengs.getContent().size() > 0) {
                for (Maptuceng mt : maptucengs.getContent()) {
//                    mt = (Maptuceng) datum;
                    map = new HashMap<>();
                    for (Object object : objects) {
                        layerMap = (Map<String, Object>) object;
                        if (layerMap.get("layer").equals(mt.getId())) { //相等就进来
                            details = getIdSqlData(mt, layerMap, details);
                            if (StringUtil.isNotEmpty(mt.getLinkId()) && (StringUtils.isEmpty(details) || details.size() == 0)) {
                                tuCengDto = new TuCengDto().setId(mt.getLinkId());
                                maptucengs = tucengService.queryMaptuceng(tuCengDto, 0, 999, Sort.Direction.DESC, "id");
                                mt = maptucengs.getContent().get(0);
                                details = getIdSqlData(mt, layerMap, details);
                            }

                            map.put("layer", mt);
                            map.put("details", details);
                            result.add(map);
                        }
                    }
                }
            }

            model.clear();
            model.put("data", result);
            model.put("success", true);
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }


    private List<Map<String, Object>> getIdSqlData(Maptuceng mt, Map<String, Object> layerMap, List details) {
        if (StringUtils.isEmpty(mt)) return details;

        if (StringUtil.isEmpty(mt.getConfig())) {
            mt.setConfig("{}");
        }
        //1.获取config
        JSONObject jsonObject = JSONUtil.parseObj(mt.getConfig());
        if (jsonObject.containsKey("idSql") && StringUtil.isNotEmpty(jsonObject.get("idSql") + "")) {
            details = jdbcTemplate.queryForList(jsonObject.get("idSql").toString().replace("{id}", layerMap.get("ids").toString().replaceAll(",", "','")));
        } else {
            details = jdbcTemplate.queryForList("select id,name,type,lnglats ,property from jiyue_map_tucengdetails  " +
                    " where id in ('" + layerMap.get("ids").toString().replaceAll(",", "','") + "') ");
        }
        return details;
    }

    //模糊查询，id查询，空间查询都
    @RequestMapping("queryMapTucengDetailsByLikeName.action")
    public Map<String, Object> queryMapTucengDetailsByLikeName(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            // 关键字取得
            String keywords = request.getParameter("keywords");
            String pageIndex = request.getParameter("pageIndex");
            String pageSize = request.getParameter("pageSize");
            String pageId = request.getParameter("pageId");


            if (StringUtil.isEmpty(pageId)) {
                pageId = "";
            }

            TuCengDto tuCengDto = new TuCengDto();
            if (!StringUtil.isEmpty(pageId)) {
                tuCengDto.setType("and type <> 'root'  and type <> 'category'  ");
            }

            if (StringUtil.isEmpty(keywords)) {//没有直接返回空
                model.clear();
                model.put("data", "");
                return model;
            }

            Page<Maptuceng> maptucengs = tucengService.queryMaptuceng(tuCengDto, 0, 99999, Sort.Direction.DESC, "id");

            Map<String, Maptuceng> layerMap = new HashMap<>();

            if (maptucengs.getContent().size() > 0) {
                List<Maptuceng> list = maptucengs.getContent();
                layerMap = list.stream().collect(Collectors.toMap(Maptuceng::getId, Function.identity()));
            }

            List<MapTucengDetails> detailArray = tucengService.queryMapTucengDetailsByLikeName(keywords);
            //3.没有likeSql

            Maptuceng mt = null;
            List<Map<String, Object>> result = new ArrayList<>();
            Map<String, Object> map = null;
            List details = null;
            int i = 0;
            if (maptucengs.getContent().size() > 0) {
                for (Maptuceng datum : maptucengs.getContent()) {
                    details = new ArrayList();
                    map = new HashMap<>();
                    mt = datum;
                    if (StringUtil.isEmpty(mt.getPageId()) || mt.getPageId() == "null") {
                        mt.setPageId("");
                    }
                    if (!pageId.equals((mt.getPageId()))) continue;
                    details = getLikeSqlData(mt, keywords, detailArray, details);
                    if (StringUtil.isNotEmpty(mt.getLinkId()) && (StringUtils.isEmpty(details) || details.size() == 0)) {
                        details = getLikeSqlData(layerMap.get(mt.getLinkId()), keywords, detailArray, details);
                    }
                    map.put("layer", mt);
                    map.put("details", details);
                    result.add(map);
                }
            }

            model.clear();
            model.put("data", result);
            model.put("success", true);
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }


    private List<Map<String, Object>> getLikeSqlData(Maptuceng mt, String keywords, List<MapTucengDetails> detailArray, List details) {
        if (StringUtils.isEmpty(mt)) return details;
        if (StringUtil.isEmpty(mt.getConfig())) {
            mt.setConfig("{}");
        }
        //1.获取config
        JSONObject jsonObject = JSONUtil.parseObj(mt.getConfig());
        //2.判断有无likeSql
        if (jsonObject.containsKey("likeSql") && StringUtil.isNotEmpty(jsonObject.get("likeSql") + "")) {
            details = jdbcTemplate.queryForList(jsonObject.get("likeSql").toString().replace("{keywords}", keywords));
        } else {
            System.out.println(mt.getLayername());
            details = detailArray.stream().filter(e -> {
                return e.getLayername().equals(mt.getLayername());
            }).collect(Collectors.toList());
        }

        return details;
    }


    /**
     * 查询
     *
     * @return
     * @author
     */
    @RequestMapping("queryMapPointLnglat.action")
    public Map<String, Object> queryMapPointLnglat(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            // 关键字取得
            String name = request.getParameter("name");
            String pageIndex = request.getParameter("pageIndex");
            String pageSize = request.getParameter("pageSize");

            if (StringUtil.isEmpty(pageIndex)) {
                pageIndex = "0";
            }
            if (StringUtil.isEmpty(pageSize)) {
                pageSize = "100";
            }
            String sql = "select *  from jiyue_map_tucengdetails where type='Point' and name is not null and name != '' ";
            List data = jdbcTemplate.queryForList(sql);
            model.put("data", data);
            model.put("success", true);
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }


    @RequestMapping("delMaptuceng.action")
    public Map<String, Object> delMapdikuai(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            String id = request.getParameter("id");

            String sql = " delete from jiyue_map_tuceng where id ='" + id + "'";
            jdbcTemplate.execute(sql);
            model.clear();
            model.put("success", true);
            model.put("message", "删除成功!");
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }

    @RequestMapping("updateTags.action")
    public Map<String, Object> updateTags(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            String id = request.getParameter("id");
            String tag = request.getParameter("tag");
            String sql = "update jiyue_map_tucengdetails set tags = '" + tag + "' where id ='" + id + "' ";

            jdbcTemplate.update(sql);
            model.clear();
            model.put("success", true);
            model.put("message", "更新成功");
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }


    /**
     * 保存或修改
     */
    @RequestMapping("saveOrUpdateMaptuceng.action")
    public Map<String, Object> saveOrUpdateMaptuceng(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            String type = request.getParameter("type");       //c(新增);u(修改),d(删除)
            String jsonData = request.getParameter("jsonData");
            Maptuceng maptuceng = JSONUtil.toBean(jsonData, Maptuceng.class);

            if (StringUtil.isEmpty(type)) {
                throw new Exception("请填写操作类型！");
            }

            if (!StringUtil.isEmpty(type) && "c".equals(type)) {
                tucengService.saveMaptuceng(maptuceng);
            } else if (!StringUtil.isEmpty(type) && "d".equals(type)) {
                if ("root".equals(maptuceng.getType())) {
                    throw new Exception("根节点不能删除！");
                }
                String sql = " delete from jiyue_map_tuceng where id ='" + maptuceng.getId() + "'";
                jdbcTemplate.execute(sql);
            } else if (!StringUtil.isEmpty(type) && "u".equals(type)) {
                tucengService.saveMaptuceng(maptuceng);
            }


            model.clear();
            model.put("success", true);
            model.put("message", "保存成功!");
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }


    /**
     * 保存或修改
     */
    @RequestMapping("saveOrUpdateMaptucengPage.action")
    public Map<String, Object> saveOrUpdateMaptucengPage(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            String type = request.getParameter("type");       //c(新增);u(修改),d(删除)
            String jsonData = request.getParameter("jsonData");
            MapTucengPage mapTcPage = JSONUtil.toBean(jsonData, MapTucengPage.class);

            List<Map<String, Object>> list = null;
            if (StringUtil.isEmpty(type)) {
                throw new Exception("请填写操作类型！");
            }
            if (!StringUtil.isEmpty(type) && "c".equals(type)) {
                tucengService.saveMapTucengPage(mapTcPage);
                //添加根节点
                Maptuceng maptuceng = new Maptuceng();
                maptuceng.setType("root");
                maptuceng.setShow("1");
                maptuceng.setPageId(mapTcPage.getId());
                maptuceng.setName(mapTcPage.getName());
                maptuceng.setId(UUID.randomUUID().toString());
                tucengService.saveMaptuceng(maptuceng);
            } else if (!StringUtil.isEmpty(type) && "d".equals(type)) {
                String sql = " delete from jiyue_map_tuceng_page where id ='" + mapTcPage.getId() + "'";
//                this.baseService.DBExec(sql);
                jdbcTemplate.execute(sql);
            } else if (!StringUtil.isEmpty(type) && "u".equals(type)) {
//                this.baseService.update(mapTcPage);
                tucengService.saveMapTucengPage(mapTcPage);
            } else if (!StringUtil.isEmpty(type) && "r".equals(type)) {
                String sql = " select *  from jiyue_map_tuceng_page where 1=1 ";
                if (!StringUtil.isEmpty(mapTcPage.getId())) {
                    sql += " and id = '" + mapTcPage.getId() + "' ";
                }
                list = jdbcTemplate.queryForList(sql);
            }

            model.clear();
            model.put("success", true);
            if ("r".equals(type)) {
                model.put("data", list);
            } else {
                model.put("message", "保存成功!");
            }
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }


    @RequestMapping("updateMapTuCengOrder.action")
    public Map<String, Object> updateMapTuCengOrder(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();

        try {
            String jsonData = request.getParameter("jsonData");
//            List<Maptuceng> maptucengs = JsonUtils.fromJson(jsonData, new TypeToken<List<Maptuceng>>() {
//            }, "yyyy-MM-dd");
            JSONArray objects = JSONUtil.parseArray(jsonData);
            List<Maptuceng> maptucengs = JSONUtil.toList(objects, Maptuceng.class);
            Maptuceng entity;
            for (Maptuceng maptuceng : maptucengs) {
//                entity = (Maptuceng) baseService.getObjByStrId(Maptuceng.class, maptuceng.getId());
//                CopyUtil.copyPropertiesIgnoreNull(maptuceng, entity);
//                this.baseService.update(entity);
                tucengService.saveMaptuceng(maptuceng);
            }
            model.clear();
            model.put("success", true);
            model.put("message", "保存成功!");
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }


    @RequestMapping(value = "saveMaptucengDetail.action", method = {RequestMethod.POST})
    public Map<String, Object> saveMaptucengDetail(String jsonData) {
        Map<String, Object> model = new HashMap<>();
        try {
            JSONArray details = JSONUtil.parseArray(jsonData);
            List<MapTucengDetails> maptucengs = JSONUtil.toList(details, MapTucengDetails.class);
            long start = System.currentTimeMillis();

            for (MapTucengDetails maptuceng : maptucengs) {
                tucengService.saveMapTucengDetails(maptuceng);
            }
//            MapTucengDetails map = null;
//            for (int i = 0; i < details.size(); i++) {
//                map = new MapTucengDetails();
//                map.setId(details.get(i).get("id"));
//                map.setLayername(details.get(i).get("layername"));
//                map.setLnglats(details.get(i).get("lnglats"));
//                map.setName(details.get(i).get("name"));
//
//                map.setProperty(details.get(i).get("property"));
//                map.setShow(details.get(i).get("show"));
//                map.setType(details.get(i).get("type"));
//                this.baseService.insert(map);
//            }

            long end = System.currentTimeMillis();
            System.out.println("时间============================" + (end - start));

            model.clear();
            model.put("success", true);
            model.put("message", "保存成功!");
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }

    @RequestMapping("saveMaptucengStyle.action")
    public Map<String, Object> saveMaptucengStyle(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            String jsonData = request.getParameter("jsonData");
            MaptucengStyle mapTcPage = JSONUtil.toBean(jsonData, MaptucengStyle.class);

            mapTcPage.setUpdatetime(new Date());
            tucengService.saveMaptucengStyle(mapTcPage);

            model.clear();
            model.put("success", true);
            model.put("message", "保存成功!");
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }

    /**
     * @param model
     * @return根据id查询jiyue_map_tucengdetails 信息
     */
    @RequestMapping("getMaptucengDetailById.action")
    public Map<String, Object> getMaptucengDetailById(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        try {
            String id = request.getParameter("id");
            if (StringUtil.isNotEmpty(id)) {
                id = id.replace(",", "','");
            }
            String sql = " select * from  jiyue_map_tucengdetails where id in ('" + id + "') ";
            List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql);
            model.clear();
            model.put("success", true);
            model.put("data", list);
        } catch (Exception e) {
            model.put("success", false);
            model.put("message", e.getMessage());
            e.printStackTrace();
        }
        return model;
    }


    /**
     * 上传上报计划明细数据
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("readJsonData.action")
    public void readJsonData(HttpServletRequest request, HttpServletResponse response, DefaultMultipartHttpServletRequest multipartRequest, Map<String, Object> model) throws Exception {
        String filedName = "upload_file";
        MultipartFile file = multipartRequest.getFile(filedName);
        model.put("success", true);
        model.put("message", "成功");

        MessageUtil.successByAjax(response, JSONUtil.toJsonStr(model));

    }


}
